<template>
  <van-form validate-trigger="onBlur" :model="loginForm" @submit="handleLogin">
    <van-cell-group inset>
      <van-field
        v-model="loginForm.email"
        name="email"
        left-icon="contact-o"
        label="邮箱"
        placeholder="请输入邮箱!"
        :rules="loginRules.email"
      />
      <van-field
        v-model="loginForm.password"
        left-icon="records-o"
        label="密码"
        type="password"
        name="password"
        placeholder="请输入密码!"
        :rules="loginRules.password"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button :loading="isLoading" round block type="primary" native-type="submit">
        启动!
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import { defineProps, reactive, ref, watch, defineEmits } from 'vue'
import { showNotify } from 'vant'
import { useRouter } from 'vue-router'
import { useSystemStore } from '@/stores'
import { sendCaptcha, register, login, updatePassword } from '@/api/user'
import _ from 'lodash-es'
const router = useRouter();
const systemStore = useSystemStore()
const emailPattern = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/
const props = defineProps({
  tabActive: {
    type: Number,
    required: true,
    default: 0
  }
})
watch(
  () => props.tabActive,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      loginForm.email = ''
      loginForm.password = ''
    }
  }
)
const isLoading = ref(false)
// 登录表单
const loginForm = reactive({
  email: '',
  password: '',
  remember: false
})
// 登录表单验证规则
const loginRules = reactive({
  email: [
    {
      required: true,
      message: '邮箱不能为空',
      validator: (value) => {
        if (!emailPattern.test(value)) {
          return '邮箱格式不正确'
        } else {
          return
        }
      }
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      validator: (value) => {
        if (value.length < 6 || value.length > 20) {
          return '密码应为6到20位。'
        } else {
          return
        }
      }
    }
  ]
})
// 登录处理
const handleLogin = async () => {
  if (!loginForm.email || !loginForm.password) {
    return
  }
  try {
    isLoading.value = true
    const res = await login({
      email: loginForm.email,
      password: loginForm.password
    })

    if (res.code === 200) {
      // 获取 systemStore
      const systemStore = useSystemStore()

      // 设置 token
      systemStore.setToken(res.token)
      localStorage.setItem('token', res.token)

      // 设置权限
      systemStore.setPermissions(res.permissions)

      // 设置用户角色 - 确保正确设置
      if (res.permissions && res.permissions.includes('ROOT')) {
        systemStore.setUtype('ROOT')
      } else if (res.permissions && res.permissions.length > 0) {
        systemStore.setUtype(res.permissions[0])
      } else {
        systemStore.setUtype('default')
      }

      localStorage.setItem('seer_session', res.session)
      localStorage.setItem('isRead', true)

      showNotify({
        type: 'success',
        message: '登录成功'
      })

      // 生成动态路由
      await systemStore.generateRoutes()

      // 计算重定向的URL
      let redirectPath = router.currentRoute.value.query.redirect || '/'

      // 确保重定向URL是相对路径
      if (redirectPath.startsWith('http')) {
        const url = new URL(redirectPath)
        redirectPath = url.pathname + url.search + url.hash
      }

      // 清除URL中的login部分
      window.history.replaceState(null, '', '/')

      // 然后导航到目标路径
      setTimeout(() => {
        router.replace(redirectPath)
      }, 10)
    }
  } catch (error) {
    showNotify({
      type:'danger',
      message: error.message
    })
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped />
